#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import decimal
import json
from decimal import Decimal

import akshare as ak
import requests
from gm.api import history, current, stk_get_daily_mktvalue, stk_get_daily_mktvalue_pt
from gm.enum import ADJUST_PREV
from sqlalchemy.dialects.mysql import DECIMAL

from web.api.base_api import BaseApi
from web.constants.datetime_format import DatetimeFormat
from web.constants.python_api_result import PythonApiResult
from web.models.stock_info import StockInfo
from web.models.stock_transaction_data import StockTransactionData
from web.models.stock_transaction_data_all import StockTransactionDataAll
from web.util.datetime_util import DatetimeUtil


class StockTransactionDataApi(BaseApi):
    """
    股票数据api
    """

    def write_stock_transaction_data_by_date(self, begin_date: str, end_date: str):
        """
        调用myquant接口，根据开始时间和结束时间保存股票数据
        """

        stock_info_list: list = self.stock_info_service.find_all()

        if stock_info_list is not None and len(stock_info_list) > 0:
            for stock_info in stock_info_list:
                prefix_code = stock_info.url_param[0:2]
                _code = None
                if prefix_code == 'sh':
                    _code = 'SHSE.' + stock_info.code_
                if prefix_code == 'sz':
                    _code = 'SZSE.' + stock_info.code_
                result_list: list = history(symbol=_code, frequency='1d', start_time=begin_date,  end_time=end_date, fields='eob, open, last_close, close, low, high, amount, volume', adjust=ADJUST_PREV, df= False)

                # 插入记录
                stock_transaction_data_list = list()
                if result_list is not None and len(result_list) > 0:
                    for result in result_list:
                        dict_values = result#.values().mapping
                        stock_transaction_data = StockTransactionData()
                        stock_transaction_data.code_= stock_info.code_
                        stock_transaction_data.date_ = dict_values['eob']
                        stock_transaction_data.open_price = dict_values['open']
                        stock_transaction_data.highest_price = dict_values['high']
                        stock_transaction_data.lowest_price = dict_values['low']
                        stock_transaction_data.close_price = dict_values['close']
                        stock_transaction_data.volume = dict_values['volume']
                        stock_transaction_data.turnover = dict_values['amount']
                        stock_transaction_data_list.append(stock_transaction_data)
                    self.stock_transaction_data_service.batch_insert(stock_transaction_data_list)
        print(PythonApiResult.FINISH)

    def find_real_stock_transaction_data_by_code(self, code: str) -> str:
        """
        根据code，返回实时数据
        """

        stock_info: StockInfo = self.stock_info_service.find_by_code(code)

        prefix_code: str = stock_info.url_param[0:2]
        _code: str = None
        if prefix_code == 'sh':
            _code = 'SHSE.' + stock_info.code_
        if prefix_code == 'sz':
            _code = 'SZSE.' + stock_info.code_
        result_list = current(symbols=_code)

        stock_transaction_data: StockTransactionData = StockTransactionData()
        stock_transaction_data.code_= code
        stock_transaction_data.date_ = DatetimeUtil.datetime_to_str(result_list[0]['created_at'], DatetimeFormat.Date_Format)
        stock_transaction_data.open_price = result_list[0]['open']
        stock_transaction_data.highest_price = result_list[0]['high']
        stock_transaction_data.lowest_price = result_list[0]['low']
        stock_transaction_data.close_price = result_list[0]['price']
        stock_transaction_data.volume = result_list[0]['cum_volume']
        stock_transaction_data.turnover = result_list[0]['cum_amount']
        json_str = json.dumps(stock_transaction_data, ensure_ascii=False, default=lambda obj: obj.__dict__)
        print(json_str)

    def find_real_code_and_total_market_value_by_code_list(self, code_list_str: str):
        """
        单次返回所有沪深京 A 股上市公司的实时行情数据
        """

        code_list: list = code_list_str.split(',')
        param_code_list: list = list()
        for code in code_list:
            stock_info: StockInfo = self.stock_info_service.find_by_code(code)
            prefix_code: str = stock_info.url_param[0:2]
            _code: str = None
            if prefix_code == 'sh':
                _code = 'SHSE.' + stock_info.code_
            if prefix_code == 'sz':
                _code = 'SZSE.' + stock_info.code_
            param_code_list.append(_code)

        result_list = current(param_code_list)
        stock_transaction_data_all_list: list = list()
        for row in result_list:
            code: str = row['symbol'][5:]
            current_price: float = row['price']
            date: str = DatetimeUtil.datetime_to_str(datetime.datetime.now(), DatetimeFormat.Date_Format_With_Line)
            stock_transaction_data_all: StockTransactionDataAll = self.stock_transaction_data_all_service.stock_transaction_data_all_dao.find_last_stock_transaction_data_all_by_code_and_date(code, date)
            current_total_market_value = float(stock_transaction_data_all.total_market_value) / float(stock_transaction_data_all.close_price) * float(current_price)
            stock_transaction_data_all.total_market_value = current_total_market_value
            stock_transaction_data_all_list.append(stock_transaction_data_all)
        json_str = json.dumps(stock_transaction_data_all_list, ensure_ascii=False,
            default=lambda o: DatetimeUtil.datetime_to_str(o, DatetimeFormat.Date_Format_With_Line) if isinstance(o, datetime.datetime) else float(o) if isinstance(o, decimal.Decimal) else o.__dict__)
        print(json_str)